//
//  LeftSideViewController.m
//  SportsSocial
//
//  Created by yull on 14/10/29.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "LeftSideViewController.h"
#import "UIView+Frame.h"
#import "Interface.h"
#import "LoginView.h"
#import "WeiboSDK.h"
#import "WXApi.h"
#import <TencentOpenAPI/QQApi.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "Interface.h"
#import <UIImageView+WebCache.h>
#import "LeftSideUserInfoCell.h"
#import "LeftCell.h"
#import "LoginRegistNet.h"
#import "UserIMNet.h"
#import "UserNet.h"

@interface LeftSideViewController () <UITableViewDataSource,UITableViewDelegate,LoginViewDelegate,TencentSessionDelegate,WXApiDelegate>

@property (nonatomic, strong) UITableView *leftTableView;

@property (nonatomic, strong) LoginView *loginView;

@property (nonatomic, strong) TencentOAuth *tencentOauth;
@property (nonatomic, strong) NSArray *permissions;

@property (nonatomic, strong) UIButton *settingButton;

@end

@implementation LeftSideViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    backgroundImageView.image = [UIImage imageNamed:@"left_bg"];
    [self.view addSubview:backgroundImageView];
    
    [self initTableView];
    
    [self initSettingButton];
    
    [self initLoginView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onWeiboLogin:) name:@"SinaWeiboLoginSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onWeixinLoginSuccess:) name:@"WeixinLoginSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLogOut:) name:@"UserLogOut" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserInfoChanged:) name:@"User_Info_Changed" object:nil];
}

- (void)initTableView
{
    CGFloat width = self.sideMenuViewController.leftOrgin;
    CGRect tableFrame = CGRectMake(0, 0, SCREEN_WIDTH - width, self.view.height -40);
    
    self.leftTableView = [[UITableView alloc] initWithFrame:tableFrame];
    self.leftTableView.backgroundColor = [UIColor clearColor];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.leftTableView];

    self.leftTableView.tableFooterView = [[UIView alloc] init];
    
    self.leftTableView.hidden = YES;
}

- (void)initSettingButton
{
    CGRect rect = CGRectMake(10, self.view.height - 40, 80, 40);
    self.settingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.settingButton.backgroundColor = [UIColor clearColor];
    self.settingButton.frame = rect;
    [self.settingButton setImage:[UIImage imageNamed:@"left_icon7"] forState:UIControlStateNormal];
    [self.settingButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.settingButton setTitle:@"设置" forState:UIControlStateNormal];
    self.settingButton.titleLabel.font = [UIFont boldSystemFontOfSize:20.0f];
    [self.settingButton addTarget:self action:@selector(onClickSettingButton:) forControlEvents:UIControlEventTouchUpInside];
    self.settingButton.hidden = YES;
    [self.view addSubview:self.settingButton];
}

- (void)initLoginView
{
    CGFloat width = self.view.width - self.sideMenuViewController.leftOrgin;
    CGFloat height = self.view.height - self.sideMenuViewController.topOrgin * 2;
    
    CGRect rect = CGRectMake(0, self.sideMenuViewController.topOrgin, width, height);
    
    self.loginView = [[LoginView alloc] initWithFrame:rect];
    self.loginView.delegate = self;
    [self.view addSubview:self.loginView];
}

#pragma mark -
#pragma mark UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 180.0f;
    }
    return 44.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        LeftSideUserInfoCell *infoCell = [tableView dequeueReusableCellWithIdentifier:@"infoCell"];
        if (!infoCell) {
            infoCell = [[LeftSideUserInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"infoCell"];
        }
        [infoCell drawCell];
        return infoCell;
    }else {
        LeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"leftCell"];
        if(!cell) {
            cell = [[LeftCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"leftCell"];
            cell.backgroundColor = [UIColor clearColor];
            cell.textLabel.textColor = [UIColor whiteColor];
            cell.textLabel.font = [UIFont boldSystemFontOfSize:20.0f];
        }
        
        cell.textLabel.text = [self getTitleAtRow:indexPath.row-1];
        cell.imageView.image = [UIImage imageNamed:[self getImageNameAtRow:indexPath.row-1]];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;

    UIViewController *destViewController = [self getController:row];
    
    UITabBarController *tabbarController = (UITabBarController *)self.sideMenuViewController.contentViewController;
    
    UINavigationController *contentViewController = (UINavigationController *)[tabbarController  selectedViewController];
    
    [contentViewController pushViewController:destViewController animated:NO];
    
    [self.sideMenuViewController hideMenuViewController];
}

#pragma mark - help

- (NSString *)getTitleAtRow:(NSInteger)row
{
    switch (row) {
        case 0:
            return @"我的好友";
            break;
        case 1:
            return @"我的关注";
            break;
        case 2:
            return @"我的相册";
            break;
        case 3:
            return @"我的运动计划";
            break;
        case 4:
            return @"我的俱乐部";
            break;
        default:
            return nil;
            break;
    }
}

- (NSString *)getImageNameAtRow:(NSInteger)row
{
    switch (row) {
        case 0:
            return @"left_icon1";
            break;
        case 1:
            return @"left_icon2";
            break;
        case 2:
            return @"left_icon3";
            break;
        case 3:
            return @"left_icon4";
            break;
        case 4:
            return @"left_icon5";
            break;
        case 5:
            return @"left_icon6";
            break;
        default:
            return nil;
            break;
    }
}

- (UIViewController *)getController:(NSInteger)row
{
    switch (row) {
        case 0:
            return [Interface createMyInfoViewController];
            break;
        case 1:
            return [Interface createFriendViewController];
            break;
        case 2:
            return [Interface createNoticeViewController];
            break;
        case 3:
            return [Interface createPhotoViewController];
            break;
        case 4:
            return [Interface createSportPlanViewController];
            break;
        case 5:
            return [Interface createGroupListViewController];
            break;
        default:
            return nil;
            break;
    }

}

#pragma mark - Action
- (void)onClickSettingButton:(id)sender
{
    UIViewController *settingViewController = [Interface createSettingViewController];
    
    UITabBarController *tabbarController = (UITabBarController *)self.sideMenuViewController.contentViewController;
    
    UINavigationController *contentViewController = (UINavigationController *)[tabbarController  selectedViewController];
    
    [contentViewController pushViewController:settingViewController animated:NO];
    
    [self.sideMenuViewController hideMenuViewController];
}

#pragma mark - LoginViewDelegate
- (void)onNormalLogin
{
    UIViewController *loginViewController = [Interface createLoginViewController];
    
    UITabBarController *tabbarController = (UITabBarController *)self.sideMenuViewController.contentViewController;
    
    UINavigationController *contentViewController = (UINavigationController *)[tabbarController  selectedViewController];
    
    [contentViewController pushViewController:loginViewController animated:NO];
    
    [self.sideMenuViewController hideMenuViewController];
}

- (void)onRegister
{
    UIViewController *loginViewController = [Interface createRegistViewController];
    
    UITabBarController *tabbarController = (UITabBarController *)self.sideMenuViewController.contentViewController;
    
    UINavigationController *contentViewController = (UINavigationController *)[tabbarController  selectedViewController];
    
    [contentViewController pushViewController:loginViewController animated:NO];
    
    [self.sideMenuViewController hideMenuViewController];
}

- (void)onQQLogin
{
    BOOL isSafari = NO;
    if (![QQApi isQQInstalled] || ![QQApi isQQSupportApi]) {
        isSafari = YES;
    }
    
    if (!_tencentOauth) {
        _tencentOauth = [[TencentOAuth alloc] initWithAppId:@"1104446359" andDelegate:self];
        [_tencentOauth setRedirectURI:@"http://www.qq.com"];
        _permissions = [NSArray arrayWithObjects:@"get_user_info",@"get_simple_userinfo", @"add_t", nil];
    }

    [_tencentOauth authorize:_permissions inSafari:isSafari];
}

- (void)onSinaWeiboLogin
{
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"https://api.weibo.com/oauth2/default.html";
    request.scope = @"all"; 
    [WeiboSDK sendRequest:request];
}

- (void)onWeixinLogin
{
    SendAuthReq* req = [[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"123" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendAuthReq:req viewController:self delegate:self];
}

#pragma mark - TencentSessionDelegate
/**
 * 登录成功后的回调
 */
- (void)tencentDidLogin
{
    NSLog(@"QQ登陆成功!");
    
    NSString *userId = self.tencentOauth.openId;
    NSString *accessToken = self.tencentOauth.accessToken;		
    
    [LoginRegistNet loginByQQWithAccessToken:accessToken openId:userId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dataDict = [responseObject objectForKey:@"data"];
            CurrentUser *currentUser = [CurrentUser shareInstance];
            [currentUser updateWithDict:dataDict];
            currentUser.isLogin = YES;
            
            [[UserIMNet shareInstance] login];
            
            [UserNet updateIOSdeviceTokenSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"devicetoken更新成功！");
            } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"devicetoken更新失败！");
            }];
            
            [[DBManager shareInstance] openDataBaseByUserId:[CurrentUser shareInstance].userId];
            
            [self handleLoginSuccess];
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.sideMenuViewController showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.sideMenuViewController showText:@"网络连接失败" time:2];
        });
    }];
}
/**
 * 登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
    NSLog(@"QQ登陆失败!");
}
/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork
{
    NSLog(@"QQ登陆网络有问题!");
}

- (void)onWeiboLogin:(NSNotification *)notification
{
    NSString *userId = [notification.userInfo objectForKey:@"userId"];
    NSString *accessToken = [notification.userInfo objectForKey:@"accessToken"];
    
    [LoginRegistNet loginByWeiboWithAccessToken:accessToken uid:userId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dataDict = [responseObject objectForKey:@"data"];
            CurrentUser *currentUser = [CurrentUser shareInstance];
            [currentUser updateWithDict:dataDict];
            currentUser.isLogin = YES;
            
            [[UserIMNet shareInstance] login];
            
            [UserNet updateIOSdeviceTokenSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"devicetoken更新成功！");
            } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"devicetoken更新失败！");
            }];
            
            [[DBManager shareInstance] openDataBaseByUserId:[CurrentUser shareInstance].userId];
            
            [self handleLoginSuccess];
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.sideMenuViewController showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.sideMenuViewController showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)onWeixinLoginSuccess:(NSNotification *)notification
{
    NSString *code = [notification.userInfo objectForKey:@"code"];
    
    [LoginRegistNet getWeixinAccessTokenWithAppid:@"wxa1eb9d2fd5d150e6" secret:@"e649c38ac7589fd21d9d2656883beae1" code:code grant_type:@"authorization_code" successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *access_token = [responseObject objectForKey:@"access_token"];
        NSString *openId = [responseObject objectForKey:@"openid"];
        if (access_token.length && openId.length) {
            [self loginByWeixinAccessToken:access_token openId:openId];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.sideMenuViewController showText:@"微信授权失败！"];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.sideMenuViewController showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)loginByWeixinAccessToken:(NSString *)access_token openId:(NSString *)openId
{
    [LoginRegistNet loginByWeixinWithAccessToken:access_token openId:openId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dataDict = [responseObject objectForKey:@"data"];
            CurrentUser *currentUser = [CurrentUser shareInstance];
            [currentUser updateWithDict:dataDict];
            currentUser.isLogin = YES;
            
            [[UserIMNet shareInstance] login];
            
            [UserNet updateIOSdeviceTokenSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"devicetoken更新成功！");
            } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"devicetoken更新失败！");
            }];
            
            [[DBManager shareInstance] openDataBaseByUserId:[CurrentUser shareInstance].userId];
            
            [self handleLoginSuccess];
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.sideMenuViewController showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.sideMenuViewController showText:@"网络连接失败" time:2];
        });
    }];
}

#pragma mark - 用户资料变更
- (void)onUserInfoChanged:(NSNotification *)notification
{
    [self.leftTableView reloadData];
}

#pragma mark - 登陆成功
- (void)handleLoginSuccess
{
    self.loginView.hidden = YES;
    self.leftTableView.hidden = NO;
    self.settingButton.hidden = NO;
    [self.leftTableView reloadData];
}

#pragma mark - 退出登录
- (void)onLogOut:(NSNotification *)notification
{
    self.loginView.hidden = NO;
    self.leftTableView.hidden = YES;
    self.settingButton.hidden = YES;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
